package com.crm.service;

import com.crm.entity.Role;
import com.crm.entity.User;
import com.crm.repository.UserRepository;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;


@Service("userService")
public class IUserServiceImpl implements IUserService {

    @Resource
    UserRepository userRepository;

    @Override
    public User login(String usrName, String usrPassword) {
        return userRepository.findByUsrNameAndUsrPassword(usrName, usrPassword);
    }

    @Override
    @CachePut(value = "saveUser", keyGenerator = "keyGenerator", unless = "#result == null")
    public void saveUser(User user) {
        userRepository.save(user);
    }

    @Override
    public void deleteUser(Integer usrId) {
        userRepository.deleteById(usrId);
    }

    @Override
    public User getUser(Integer usrId) {
        return userRepository.findById(usrId).get();
    }

    @Override
    public User getUserByUsrName(String usrName) {
        return userRepository.findUserByUsrName(usrName);
    }

    @Override
    @Cacheable(value = "users", keyGenerator = "keyGenerator", condition = "#roleId!=0")
    public Page<User> findUsers(String usrName, Integer roleId, Pageable pageable) {
        Specification<User> specification = new Specification<User>() {
            @Override
            public Predicate toPredicate(Root<User> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicates = new ArrayList<>();
                if (usrName != null && !usrName.equals("")) {
                    predicates.add(criteriaBuilder.like(root.get("usrName"), "%" + usrName + "%"));
                }
                if (roleId != null && roleId != 0) {
                    Role role = new Role();
                    role.setRoleId(roleId);
                    predicates.add(criteriaBuilder.equal(root.get("role"), role));
                }
                return criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()]));
            }
        };
        return userRepository.findAll(specification, pageable);
    }

    @Override
    public String encryptPassword(Object plaintextPassword) throws IllegalArgumentException {
        Md5Hash md5Hash = new Md5Hash(plaintextPassword, "zy", 2);
        return md5Hash.toString();
    }

    @Override
    public List<User> findAll() {
        return userRepository.findAll();
    }
}
